﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;

namespace HANS_BackStage.Common
{
    public  class FormsAuthenticationHelper
    {
        public static void SignIn(string userName, bool rememberMe)
        {
            FormsAuthentication.SetAuthCookie(userName, rememberMe,"");
            RenewCurrentUser();
        }

        /// <summary>
        /// 
        /// </summary>
        public static void SignOut()
        {
            FormsAuthentication.SignOut();
        }

        public static bool IsLogin()
        {
            RenewCurrentUser();
            return HttpContext.Current.User != null;
        }

        /// <summary>
        /// 刷新用户授权数据，防止登陆后未重定向带来的问题
        /// http://stackoverflow.com/questions/2105391/how-to-set-request-isauthenticated-to-true-when-not-using-formsauthentication-re
        /// </summary>
        public static void RenewCurrentUser()
        {
            HttpCookie authCookie =
                HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
            if (authCookie != null)
            {
                FormsAuthenticationTicket authTicket = null;
                authTicket = FormsAuthentication.Decrypt(authCookie.Value);

                if (authTicket != null && !authTicket.Expired)
                {
                    FormsAuthenticationTicket newAuthTicket = authTicket;

                    if (FormsAuthentication.SlidingExpiration)
                    {
                        newAuthTicket = FormsAuthentication.RenewTicketIfOld(authTicket);
                    }
                    string userData = newAuthTicket.UserData;
                    string[] roles = userData.Split(',');

                    HttpContext.Current.User =
                        new GenericPrincipal(new FormsIdentity(newAuthTicket), roles);
                }
            }
        }
    }
}
